package com.zx.DataStructuresAndAlgorithms;

import com.zx.DataStructuresAndAlgorithms.dao.RandTest;
import com.zx.DataStructuresAndAlgorithms.dao.SysInfoSupply;

import static com.zx.DataStructuresAndAlgorithms.dao.SortSwap.swapSelect;

/**
 * @Author lovexu
 * @Date 2022/10/21 12:27
 * @ClassName SelectionSort
 * @Description 选择排序
 **/
public class SelectionSort implements SysInfoSupply {

    /**
     * 从小到大排序
     */
    public static <AnyType extends Comparable<? super AnyType> >
    void selectionSortUp(AnyType[] arr, int n) {

        for (int i = 0; i < n; i++) {
            //初始化当前最小索引为i 寻找【i，n】区间最小值
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j].compareTo(arr[minIndex]) < 0) {
                    minIndex = j;   //交换索引
                }
            }
            swapSelect(arr, i, minIndex);
        }
    }
    /**
     * 从大到小排序
     */
    public static <AnyType extends  Comparable<? super AnyType>>
    void  selectionSortDown(AnyType arr[],int n){
        for (int i = 0; i < n; i++) {
            int maxIndex=i;
            for (int j = i+1; j <n ; j++) {
                if (arr[j].compareTo(arr[maxIndex])>0){
                    maxIndex=j;
                }
            }
            swapSelect(arr,i,maxIndex);
        }
    }





    public static void main(String[] args) {

//        Float[] arr = {6.3f, 3.5f, 4.3f, 5.6f, 7.8f, 8.2f, 8.3f, 8.25f};
//        SysInfoSupply.sysInfo(arr);
//        outPut(arr);
//        Integer[] arr1 = {6, 3, 4, 5, 7, 8, 8, 9};
//        SysInfoSupply.sysInfo(arr1);
//        outPut(arr1);
//        String[]arr2={"A","C","B","E","G","H","D","F","K","I","J"};
//        SysInfoSupply.sysInfo(arr2);
//        outPut(arr2);

        //随机生成测试原始数据
        String s[]=new String[8];
        RandTest.randGenerateString(s);
        outPut(s);

        Integer integer[]=new Integer[8];
        RandTest.randGenerateInteger(integer);
        outPut(integer);

        Float fs[]=new Float[8];
        RandTest.randGenerateFloat(fs);
        outPut(fs);

        Double db[]=new Double[8];
        RandTest.randGenerateDouble(db);
        outPut(db);
    }




    public static <AnyType extends Comparable<? super AnyType>>
    void outPut(AnyType[] arr) {
        selectionSortUp(arr, arr.length);
        System.out.print("从小到大排序:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+",");
        }
        System.out.println();
        System.out.print("从大到小排序:");
        selectionSortDown(arr,8);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+",");
        }
        System.out.println();
        System.out.println();
    }
}
